package com.yuecai.modules.yc_receiver_info.service;


import com.yuecai.modules.yc_order.domain.YcOrder;
import com.yuecai.modules.yc_order.repository.YcOrderRepository;
import com.yuecai.modules.yc_receiver_info.domain.YcReceiverInfo;
import com.yuecai.modules.yc_receiver_info.repository.YcReceiverInfoRepository;
import com.yuecai.modules.yc_receiver_info.service.dto.YcReceiverInfoDto;
import com.yuecai.modules.yc_receiver_info.service.dto.YcReceiverInfoQueryCriteria;
import com.yuecai.modules.yc_receiver_info.service.mapstruct.YcReceiverInfoMapper;
import com.yuecai.utils.FileUtil;
import com.yuecai.utils.PageUtil;
import com.yuecai.utils.QueryHelp;
import com.yuecai.utils.ValidationUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @author dm
* @date 2020-05-20
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YcReceiverInfoService {

    private final YcReceiverInfoRepository ycReceiverInfoRepository;

    private final YcReceiverInfoMapper ycReceiverInfoMapper;


    private final YcOrderRepository ycOrderRepository;

    public YcReceiverInfoService(YcReceiverInfoRepository ycReceiverInfoRepository, YcReceiverInfoMapper ycReceiverInfoMapper, YcOrderRepository ycOrderRepository) {
        this.ycReceiverInfoRepository = ycReceiverInfoRepository;
        this.ycReceiverInfoMapper = ycReceiverInfoMapper;
        this.ycOrderRepository = ycOrderRepository;
    }


    public Map<String,Object> queryAll(YcReceiverInfoQueryCriteria criteria, Pageable pageable){
        Page<YcReceiverInfo> page = ycReceiverInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(ycReceiverInfoMapper::toDto));
    }



    public List<YcReceiverInfoDto> queryAll(YcReceiverInfoQueryCriteria criteria){
        return ycReceiverInfoMapper.toDto(ycReceiverInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }


    public YcReceiverInfoDto findById(Long id) {
        YcReceiverInfo ycReceiverInfo = ycReceiverInfoRepository.findById(id).orElseGet(YcReceiverInfo::new);
        ValidationUtil.isNull(ycReceiverInfo.getId(),"YcReceiverInfo","id",id);
        return ycReceiverInfoMapper.toDto(ycReceiverInfo);
    }


    @Transactional(rollbackFor = Exception.class)
    public YcReceiverInfoDto create(YcReceiverInfo resources) {
        if(resources.getDefaultSign()){
            YcReceiverInfo ycReceiverInfo = ycReceiverInfoRepository.findByUserIdAndDefaultSignTrue(resources.getUserId());
           /* if (ycReceiverInfo.size()>0){
                for (YcReceiverInfo item:ycReceiverInfo){
                    //把之前存在的重置为非默认
                    item.setDefaultSign(false);
                    ycReceiverInfoRepository.save(item);
                }
            }*/
            if (ycReceiverInfo!=null){
                //把之前存在的重置为非默认
                ycReceiverInfo.setDefaultSign(false);
                ycReceiverInfoRepository.save(ycReceiverInfo);
            }
        }
        return ycReceiverInfoMapper.toDto(ycReceiverInfoRepository.save(resources));
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(YcReceiverInfo resources) throws Exception {
        Optional<YcReceiverInfo> byId1 = ycReceiverInfoRepository.findById(resources.getId());
        if (!byId1.isPresent()){
            throw new Exception("该收货地址不存在！");
        }
        YcReceiverInfo ycReceiverInfo = byId1.get();
        if(resources.getDefaultSign()){
            YcReceiverInfo receiverDefault = ycReceiverInfoRepository.findByUserIdAndDefaultSignTrue(resources.getUserId());
            if (receiverDefault!=null){
                //把之前存在的重置为非默认
                Long id = receiverDefault.getId();
                Long id1 = ycReceiverInfo.getId();
                if (!id.equals(id1)){
                    //当前要修改的地址不是默认地址 把默认地址重置为非默认
                    receiverDefault.setDefaultSign(false);
                    ycReceiverInfoRepository.save(ycReceiverInfo);
                }
            }
        }
        ycReceiverInfo.copy(resources);
        ycReceiverInfoRepository.save(ycReceiverInfo);
    }


    public void deleteAll(Long[] ids) throws Exception {
        for (Long id : ids) {
            List<YcOrder> byReceiverId = ycOrderRepository.findByReceiverId(id);
            if (CollectionUtils.isNotEmpty(byReceiverId)){
                throw new Exception("请删除该地址下的订单!");
            }
            ycReceiverInfoRepository.deleteById(id);
        }
    }

    
    public void delete(Long id) {
        ycReceiverInfoRepository.deleteById(id);
    }

    
    public Optional<YcReceiverInfo> findReceiverById(Long id) {
        return ycReceiverInfoRepository.findById(id);
    }

    
    public void download(List<YcReceiverInfoDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YcReceiverInfoDto ycReceiverInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户id", ycReceiverInfo.getUserId());
            map.put("省code_市code", ycReceiverInfo.getCityCode());
            map.put("区县code", ycReceiverInfo.getCountyCode());
            map.put("地址", ycReceiverInfo.getAddress());
            map.put("收货人姓名", ycReceiverInfo.getReceiver());
            map.put("收货人手机号", ycReceiverInfo.getPhoneNum());
            map.put("邮编", ycReceiverInfo.getPostCode());
            map.put("地址的条目是否默认标识，0不是，1是", ycReceiverInfo.getDefaultSign());
            map.put("时间", ycReceiverInfo.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    /**
     * 查询默认 收货地址
     * @param memberId
     * @return
     */
    public YcReceiverInfo findByMemberIdAndDefaultSignTrue(Long memberId) {
        YcReceiverInfo receiverInfo = ycReceiverInfoRepository.findByUserIdAndDefaultSignTrue(memberId);
        if (receiverInfo!=null){
            return receiverInfo;
        }
        return null;
    }


    /**
     * 查询默认 收货地址
     * @param memberId
     * @return
     */
    
    public YcReceiverInfo findByMemberIdAndId(Long memberId,Long id) throws Exception {
        Optional<YcReceiverInfo> defaultSign = ycReceiverInfoRepository.findByIdAndUserId(memberId,id);
        if (defaultSign.isPresent()){
            return defaultSign.get();
        }
        throw new Exception("收货地址不存在 ！");
    }
}